package com.roidrage.modules
{
	import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    
    import mx.events.ModuleEvent;
    import mx.modules.IModuleInfo;
    import mx.modules.ModuleManager;

    [Event(name="complete", type="flash.events.Event")]
    public class DynamicFactory extends EventDispatcher
    {
        private var moduleInfo:IModuleInfo;
        
        private var typeToCreate:String;
        private var moduleUrl:String;
        
        private var _createdInstance:*;
        
        public function DynamicFactory(target:IEventDispatcher=null)
        {
            super(target);
        }
        
        public function createFromModule(type:String, fromModule:String):void
        {
            typeToCreate = type;
            moduleUrl = fromModule;
            
            //First we have to load the module so that we can use it
            loadModule(moduleUrl);
        }
        
        private function loadModule(url:String):void
        {
            moduleInfo = ModuleManager.getModule(url);
            
            moduleInfo.addEventListener(ModuleEvent.READY, moduleReadyHandler);
            moduleInfo.addEventListener(ModuleEvent.PROGRESS, moduleProgressHandler);
            moduleInfo.addEventListener(ModuleEvent.ERROR, moduleErrorHandler);
            moduleInfo.load();
        }
        
        protected function moduleReadyHandler(event:ModuleEvent):void
        {
            //Now that we have our module we need to create an instance of the
            //factory that it contains
            var factory:IFactoryModule = moduleInfo.factory.create() as IFactoryModule;
            
            //Now we have to create our instance from the factory
            _createdInstance = factory.create(typeToCreate);
            
            dispatchEvent(new Event(Event.COMPLETE));
        }
        
        protected function moduleProgressHandler(event:ModuleEvent):void
        {
            //TODO: Send progress events
            this.dispatchEvent(event);
        }
        
        protected function moduleErrorHandler(event:ModuleEvent):void
        {
            //TODO: Send error events
        }
        
        public function get createdInstance():*
        {
            return _createdInstance;
        }
    }

}